<template>
  <div class="exist-model">
    <el-input
      placeholder="源对象名称/目标模型名称"
      class="search"
      v-model="sourceName"
      size="small"
    >
      <el-button
        @click="searchSourceList"
        slot="append"
        type="primary"
        icon="el-icon-search"
      ></el-button>
    </el-input>
    <el-table
      size="medium"
      :data="sourceList"
      :cell-style="{ color: '#333333' }"
      :header-cell-style="{ background: '#F3F4F7', color: '#000000' }"
      height="485"
    >
      <el-table-column
        prop="syncObject"
        label="源对象名称"
        align="center"
      ></el-table-column>
      <el-table-column label="目标模型" align="center">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.targetModelId"
            @change="changeTargetModel(scope.row)"
            size="mini"
          >
            <el-option
              v-for="item in modelList"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-link
            :underline="false"
            type="primary"
            class="source-edit"
            @click.native.prevent="openMap(scope.row)"
            >维护映射</el-link
          >
          <el-link
            :underline="false"
            type="primary"
            class="source-edit"
            @click.native.prevent="deleteSource(scope.row.mappingTableId)"
            >删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="model-btns-wrapper">
      <div class="model-btns">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </div>
    </div>
    <map-list
      :innerVisible="innerVisible"
      :currentMapItem="currentMapItem"
      @closeConfigBox="closeConfigBox"
      @saveMap="saveMap"
    ></map-list>
  </div>
</template>
<script>
import { deepClone } from "@/plugins/utils";
import MapList from "./mapList.vue";
import { mapState, mapMutations } from "vuex";
export default {
  components: {
    MapList,
  },
  data() {
    return {
      total: 0,
      sourceName: "", // 任务名称
      sourceList: [], // 已有模型-源对象列表-展示
      edit_sourceList: [], //已有模型-源对象列表-编辑后
      modelList: [], // 目标模型列表
      innerVisible: false, // 显示映射弹窗
      currentMapItem: {},
      saveDisabled: false,
    };
  },
  computed: {
    ...mapState({
      taskId: (state) => state.dataCollection.taskId,
      conifgBoxIsOpen: (state) => state.dataCollection.conifgBoxIsOpen,
      currentTab: (state) => state.dataCollection.currentTab,
    }),
  },
  methods: {
    ...mapMutations({
      toggleConfigBoxDialog: "dataCollection/toggleConfigBoxDialog",
    }),
    // 获取源对象列表
    getSourceList() {
      this.$axios
        .post(`${this.$api.dataCollection.getSourceList}?taskId=${this.taskId}`)
        .then((res) => {
          let { code, message, data } = res.data;
          console.log(data);
          if (code !== 200) {
            this.$message.warning(message);
            return;
          }
          let list = data;
          this.edit_sourceList = deepClone(list);
          this.sourceList = deepClone(list);
          this.saveDisabled = this.edit_sourceList.length ? false : true;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取目标模型列表
    getTargetModelList() {
      let params = {
        code: "target_object",
        source: 3,
      };
      this.$axios
        .post(this.$api.dataCollection.getAllSourceList, params)
        .then((res) => {
          let { code, message, data } = res.data;
          if (code !== 200) {
            this.$message.warning(message);
            return;
          }
          this.modelList = data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 前端搜索查询
    searchSourceList() {
      this.sourceList = this.edit_sourceList.filter((source) => {
        let { syncObject, targetModelName } = source;
        let sourceName = this.sourceName.toLowerCase();
        return (
          syncObject.toLowerCase().includes(sourceName) ||
          targetModelName.toLowerCase().includes(sourceName)
        );
      });
    },
    // 撤销修改
    reset() {
      this.getSourceList();
      this.sourceName = "";
    },
    closeDialog() {
      this.toggleConfigBoxDialog(false);
    },
    // 保存当前映射修改
    saveMap(params) {
      let { mappingTableId, mapFields, sourceFields, targetFields } = params;
      let setMapItem = this.edit_sourceList.find(
        (source) => source.mappingTableId === mappingTableId
      );
      setMapItem.mapList = mapFields;
      setMapItem.sourceList = sourceFields;
      setMapItem.targetList = targetFields;
      let updateIndex = this.sourceList.findIndex(
        (source) => source.mappingTableId === mappingTableId
      );
      this.sourceList.splice(updateIndex, 1, setMapItem);
    },
    // 保存
    saveEdit() {
      let params = {
        taskId: this.taskId,
        mappingTableList: this.edit_sourceList,
      };
      this.$axios
        .post(this.$api.dataCollection.saveMapList, params)
        .then((res) => {
          let { code, message } = res.data;
          if (code !== 200) {
            this.$message.warning(message);
            return;
          }
          this.$message.success("保存成功!");
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 维护映射
    openMap(row) {
      if (row.targetModelId) {
        this.currentMapItem = row;
        this.innerVisible = true;
      } else {
        this.$message.warning("请先选择目标模型，然后进行映射！");
      }
    },
    // 前端删除
    deleteSource(mappingTableId) {
      console.log(mappingTableId);
      let delIndex = this.sourceList.findIndex(
        (source) => source.mappingTableId === mappingTableId
      );
      let _delIndex = this.edit_sourceList.findIndex(
        (source) => source.mappingTableId === mappingTableId
      );
      this.sourceList.splice(delIndex, 1); // 删除当前展示列表对应的项
      this.edit_sourceList.splice(_delIndex, 1); // 删除原始列表对应的项
    },
    // 同步修改列表中目标模型名称
    changeTargetModel(row) {
      row.targetModelName = this.modelList.find(
        (model) => model.key === row.targetModelId
      ).value;
      let updateIndex = this.edit_sourceList.findIndex(
        (source) => source.mappingTableId === row.mappingTableId
      );
      let setMapItem = deepClone(row);
      this.edit_sourceList.splice(updateIndex, 1, setMapItem);
      this.getMapList(row.mappingTableId, row.targetModelId).then((data) => {
        let { sourceList, targetList, mapList } = data;
        row.sourceList = sourceList;
        row.targetList = targetList;
        row.mapList = mapList;
      });
    },
    // 获取所有字段列表
    getMapList(mappingTableId, targetModelId) {
      let params = {
        mappingTableId,
        targetModelId,
      };
      return this.$axios
        .post(this.$api.dataCollection.getMapList, params)
        .then((res) => {
          let { code, message, data } = res.data;
          if (code !== 200) {
            this.$message.warning(message);
            return;
          }
          return data;
        });
    },
    closeConfigBox() {
      this.innerVisible = false;
    },
  },
  watch: {
    currentTab: {
      handler: function (val) {
        if (val == 2) {
          Object.assign(this.$data, this.$options.data());
          this.getSourceList();
          this.getTargetModelList();
        }
      },
      immediate: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.source-edit {
  padding: 0 10px;
  & + .source-edit {
    border-left: 1px solid #dddddd;
  }
}
/deep/ .el-table__append-wrapper {
  padding: 10px;
}

.el-pagination {
  float: right;
  margin-top: 20px;

  .form-input /deep/ .el-input {
    width: 200px;
  }

  /deep/ .el-input__inner {
    height: 22px;
  }
}
.search {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 300px;
}
.model-btns-wrapper {
  display: flex;
  justify-content: center;
  .model-btns {
    width: 200px;
    display: flex;
    justify-content: space-around;
    margin-top: 28px;
  }
}
</style>
